package com.jvm123.blog.servlet

import org.slf4j.Logger
import org.slf4j.LoggerFactory

import javax.servlet.*
import javax.servlet.annotation.WebFilter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @author yawn http://jvm123.com
 *     2019/11/3 14:36
 */
@WebFilter(urlPatterns = "/*", asyncSupported = true)
class AuditFilter implements Filter {

    Logger logger = LoggerFactory.getLogger(AuditFilter.class)

    @Override
    void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest
        HttpServletResponse response = (HttpServletResponse) servletResponse
        String uri = request.getRequestURI()
        String referer = request.getHeader("Referer")
        String host = request.getHeader("Host")
        String xRealIp = request.getHeader("x-real-ip")
        String userAgent = request.getHeader("user-agent")
        int statusCode = response.getStatus()
        filterChain.doFilter(servletRequest, servletResponse)
        logger.info("{} {}, host={}, referer={}, x-real-ip={}, user-agent={}", statusCode, uri, host, referer, xRealIp, userAgent)
    }
/*
    @Override
    void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        AsyncContext asyncContext = servletRequest.startAsync()
        asyncContext.start(new Runnable() {
            @Override
            void run() {
                // 处理代码
                asyncContext.complete()
            }
        })
    }
*/

    @Override
    void destroy() {
    }
}
